<script setup lang="ts">
import { useLoadMore } from 'vue-request'
import type { IssuingInvoicesHistoryItemData, LoadMoreData } from '@/types/api'
import { fetchIssuingInvoicesHistoryListAPI } from '@/apis/fetchIssuingInvoicesHistoryList'
import { useUserInfoStore } from '@/store/userInfo'

const router = useRouter()
const userInfoStore = useUserInfoStore()

const selectedTabIndex = ref(0)
const tabConfiguration = ['叫车订单', '城际订单']

// 分页列表数据
const { dataList, loading, loadingMore, noMore, loadMore, refresh } = useLoadMore<LoadMoreData<IssuingInvoicesHistoryItemData>>(
  fetchData,
  { isNoMore: d => d?.list.length === d?.total },
)

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

/**
 * @description 分页服务函数
 */
async function fetchData(d?: LoadMoreData<IssuingInvoicesHistoryItemData>): Promise<LoadMoreData<IssuingInvoicesHistoryItemData>> {
  // 当前页数
  const _page = d?.page ? d.page + 1 : 1

  const res = await fetchIssuingInvoicesHistoryListAPI(
    {
      page: _page.toString(),
      limit: '10',
      order_type: selectedTabIndex.value === 0 ? '2' : '1',
    },
    userInfoStore.userInfo!.token!,
  )

  return {
    list: res.data?.data.data || [],
    page: _page,
    total: res.data?.data.total || 9999,
  }
}

watch(selectedTabIndex, () => refresh())

function handleViewIssuingInvoicesDetail() {
  router.push('issuingInvoicesDetail')
}
</script>

<template>
  <Tabs
    :selected-index="selectedTabIndex"
    :items="tabConfiguration"
    @change="(i: number) => selectedTabIndex = i"
  />
  <Spacer height="30" />
  <view class="px-24rpx">
    <view v-if="dataList.length === 0" class="absolute left-1/2 top-1/2 text-28rpx text-#999999 -translate-1/2">
      暂无数据
    </view>
    <IssuingInvoicesHistoryItem
      v-for="item in dataList"
      :key="item.id"
      :data="item"
      @tap="handleViewIssuingInvoicesDetail"
    />
    <uv-load-more v-if="dataList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" />
  </view>
  <Spacer height="180" />
  <uv-loading-page :loading="loading && !loadingMore" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
</template>

<route lang="yaml">
name: 'issuingInvoicesHistory'
style:
  navigationBarTitleText: '开票历史'
</route>
